/**
 * Created by shandianhaizan on 16/7/29.
 */


define(['validator'], function (validator) {

    function _controller($scope, $routeParams, $location, $timeout, httpService) {

        var id = $routeParams.id;
        var model ="_User";
        $scope.properties = [];

        $scope.remove = function(one, arr){
            arr.splice( $.inArray(one, arr), 1);
        };
        var isUpdate = function(){
            return id && id!=="new"
        };


        $scope.validation = function(arg_user){
            if(arg_user.mobilePhoneNumber && !validator.isMobilePhone(arg_user.mobilePhoneNumber, "zh-CN")){
                return {success:false, msg:"手机号格式错误"};
            }
            if(arg_user.email && !validator.isEmail(arg_user.email) ){
                return {success:false, msg:"邮箱格式错误"};
            }
            return {success:true}

        };
        $scope.save = function () {
            $scope.$broadcast('show-errors-check-validity');
            var validation = $scope.validation($scope.user);
            if(!validation.success) return $scope.msg.show(validation.msg);
            httpService.save(model, $scope.user).then(function (data) {
                $scope.msg.show(data);
                if($scope.isHandleSuccess(data) && !isUpdate()){
                    $location.path('/edit-user/'+data.data.objectId);
                }else if(data.code && data.code == 202){
                    $scope.msg.show("用户名已被注册");
                }
            });

        };

        $scope.initRole = function () {
            httpService.get("UserRole", {all:true}).then(function (data) {
                $scope.roles = data.data.data;
            });
        };





        $scope.initRole();



        $scope.reset = function () {
            $scope.$broadcast('show-errors-reset');
            $scope.user = {};
        };


        if(isUpdate()){
            $scope.editType = "编辑";
            httpService.get(model, id).then(function (data) {
                $scope.user = data.data;
            });
        }else{
            $scope.editType = "添加";
            $scope.user = {
            };
        }




    }

    return _controller;
});

